package com.me.hippy.sdk.demo.retrofitokhoot.api

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.reflect.ParameterizedType
import java.util.concurrent.TimeUnit

abstract class BaseApiManager<ApiService> {
    companion object {
        const val DEFAULT_READ_TIMEOUT_MILLIS = 8 * 1000L
        const val DEFAULT_WRITE_TIMEOUT_MILLIS = 8 * 1000L
        const val DEFAULT_CONNECT_TIMEOUT_MILLIS = 8 * 1000L
    }

    var apiService: ApiService

    init {
        val builder = Retrofit.Builder()
        builder.baseUrl(baseUrl())
        builder.addConverterFactory(converterFactory())
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        builder.client(provideOkHttp())
        val retrofit = builder.build()
        apiService = retrofit.create(
            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<ApiService>
        )
    }

    abstract fun baseUrl(): String

    open fun converterFactory(): Converter.Factory {
        return GsonConverterFactory.create()
    }

    open fun provideOkHttp(): OkHttpClient {
        val okHttpClientBuilder = OkHttpClient.Builder()
            .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
        addInterceptor(okHttpClientBuilder)
        return okHttpClientBuilder.build()
    }

    open fun addInterceptor(okHttpClientBuilder: OkHttpClient.Builder) {

    }
}